//
//  AppDelegate.m
//  Movie
//
//  Created by cjy on 16/3/21.
//  Copyright © 2016年 HY. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "TB.h"
#import "LeftMenu.h"
#import "MoreViewController.h"
#import "MovieViewController.h"
#import <AVOSCloud/AVOSCloud.h>
#import "DataBaseHandle.h"
#import "ImageTool.h"

#import "WeiboSDK.h"
#define kAppKey @"950079391"
#define KRedirectURI @"https://api.weibo.com/oauth2/default.html"



@interface WBBaseRequest ()
- (void)debugPrint;
@end

@interface WBBaseResponse ()
- (void)debugPrint;
@end

@interface AppDelegate ()<UIScrollViewDelegate>
@property (nonatomic,retain)NSMutableArray  *arrayOfImageView;
@property (nonatomic,retain)UIScrollView *scrollView;
@property (nonatomic,retain)UIPageControl *pageControl;
@property (nonatomic,retain)UIButton *buttonOfStart;


@end

@implementation AppDelegate


@synthesize wbtoken;
@synthesize wbCurrentUserID;
@synthesize wbRefreshToken;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
//    [self.window bringSubviewToFront:self.scrollView];
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:kAppKey];
        NSLog(@"%@", NSHomeDirectory());


    [AVOSCloud setApplicationId:@"RKz7riWTmdFMXIgcEjKdyw65-gzGzoHsz"
                      clientKey:@"WcUTfKpasNF8dsnLUgBHWzA5"];
    [AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions];

    
    self.window.backgroundColor = [UIColor colorWithRed:40 / 255.f green:40 / 255.f blue:40 / 255.f alpha:1];
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
    [self.window makeKeyAndVisible];
    ViewController *vc = [[ViewController alloc]init];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:vc];
    
    MovieViewController *movie = [[MovieViewController alloc]init];
    UINavigationController *navi2 = [[UINavigationController alloc]initWithRootViewController:movie];
    
    MoreViewController *music = [[MoreViewController alloc]init];
    UINavigationController *navi3 = [[UINavigationController alloc]initWithRootViewController:music];
    
    
    // 字体颜色 选中
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:12.0F], NSForegroundColorAttributeName : [UIColor colorWithRed:0.980 green:0.902 blue:0.932 alpha:1.000]} forState:UIControlStateSelected];
    
    // 字体颜色 未选中
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12.0F],  NSForegroundColorAttributeName:[UIColor lightGrayColor]} forState:UIControlStateNormal];

    


    TB *tb = [TB TBShare];
    navi.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"首页" image:[UIImage imageNamed:@"shouye"] tag:100];

    navi2.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"电影" image:[UIImage imageNamed:@"Item2"] tag:200];
    
    navi3.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"发现更多" image:[UIImage imageNamed:@"Music"] tag:300];
    tb.viewControllers = @[navi,navi2,navi3];
    tb.tabBar.selectedImageTintColor = [UIColor colorWithRed:0.971 green:0.893 blue:0.871 alpha:1.000];

    LeftMenu *left = [[LeftMenu alloc]init];
    
    
    RESideMenu *sideMenuViewController = [[RESideMenu alloc]initWithContentViewController:tb leftMenuViewController:left rightMenuViewController:nil];
    
    sideMenuViewController.backgroundImage = [UIImage imageNamed:@"beijing"];
    sideMenuViewController.menuPreferredStatusBarStyle = 1; // UIStatusBarStyleLightContent
    sideMenuViewController.delegate = self;
    
    sideMenuViewController.contentViewShadowColor = [UIColor blackColor];
    sideMenuViewController.contentViewShadowOffset = CGSizeMake(0, 0);
    sideMenuViewController.contentViewShadowOpacity = 0.6;
    sideMenuViewController.contentViewShadowRadius = 12;
    sideMenuViewController.contentViewShadowEnabled = YES;
    
    self.window.rootViewController = sideMenuViewController;
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    // 第一次进入
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"引导页"]) {
        
        [[NSUserDefaults standardUserDefaults] setBool:1 forKey:@"引导页"];
        
        self.arrayOfImageView = [NSMutableArray array];
        self.arrayOfImageView = @[@"1", @"2", @"3"].mutableCopy; //添加引导页图片
        //
        self.scrollView = [[UIScrollView alloc] init];
        [self.window addSubview:self.scrollView];  //注意:添加在window上
        self.scrollView.pagingEnabled = YES;
        self.scrollView.backgroundColor =[UIColor redColor];
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.userInteractionEnabled = YES;
        self.scrollView.frame = self.window.frame;
        self.scrollView.contentSize = CGSizeMake(self.window.frame.size.width * self.arrayOfImageView.count, 0);
        self.scrollView.delegate = self;
        
        self.pageControl = [[UIPageControl alloc] init];
        [self.window addSubview:self.pageControl];
        self.pageControl.frame = CGRectMake(0, 0, self.window.frame.size.width / 2, 40);
        self.pageControl.center = CGPointMake(self.scrollView.frame.size.width / 2, self.scrollView.frame.size.height - 40);
        self.pageControl.numberOfPages = self.arrayOfImageView.count;
        
        
        
        //for循环, 在scrollView上添加照片
        for (int i = 0; i < self.arrayOfImageView.count; i++) {
            UIImageView *imageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:self.arrayOfImageView[i]]];
            imageView1.frame = CGRectMake(self.scrollView.frame.size.width * i, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height);
            imageView1.tag = i;
            [self.scrollView addSubview:imageView1];
            imageView1.userInteractionEnabled = YES;
            
        }
        
        //引导页最后一页"开始体验"按钮, 进入APP
        self.buttonOfStart = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImageView *image = [self.window viewWithTag:2];
        [image addSubview:self.buttonOfStart];
        [self.buttonOfStart setTitle:@"开始体验" forState:UIControlStateNormal];
        
        [self.buttonOfStart setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.buttonOfStart.layer.borderWidth = 1;
        self.buttonOfStart.layer.borderColor = [[UIColor whiteColor] CGColor];
        self.buttonOfStart.layer.cornerRadius = 7;
        self.buttonOfStart.layer.masksToBounds = YES;
        self.buttonOfStart.frame = CGRectMake(0, 0, self.window.frame.size.width / 2, 40);
        self.buttonOfStart.center = CGPointMake(self.window.frame.size.width / 2, self.window.frame.size.height - 100);
        [self.buttonOfStart addTarget:self action:@selector(start:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    
    
    
    
    [[DataBaseHandle shareDataBaseHandle] open];
    [[DataBaseHandle shareDataBaseHandle] createTable];
    


    return YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    self.pageControl.currentPage = scrollView.contentOffset.x/300;
}
- (void)start:(UIButton *)button{
    
    [self.pageControl removeFromSuperview];
    [self.scrollView removeFromSuperview];
    
    
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [WeiboSDK handleOpenURL:url delegate:self];
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [WeiboSDK handleOpenURL:url delegate:self ];
}


- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        
            WBSendMessageToWeiboResponse* sendMessageToWeiboResponse = (WBSendMessageToWeiboResponse*)response;
        NSString* accessToken = [sendMessageToWeiboResponse.authResponse accessToken];
        if (accessToken)
        {
            self.wbtoken = accessToken;
        }
        NSString* userID = [sendMessageToWeiboResponse.authResponse userID];
        if (userID) {
            self.wbCurrentUserID = userID;
        }
    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        
        self.wbtoken = [(WBAuthorizeResponse *)response accessToken];
        self.wbCurrentUserID = [(WBAuthorizeResponse *)response userID];
        self.wbRefreshToken = [(WBAuthorizeResponse *)response refreshToken];
    }
 else if([response isKindOfClass:WBShareMessageToContactResponse.class])
    {
        NSString *title = NSLocalizedString(@"发送结果", nil);
        NSString *message = [NSString stringWithFormat:@"%@: %d\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode, NSLocalizedString(@"响应UserInfo数据", nil), response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil),response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                              otherButtonTitles:nil];
        WBShareMessageToContactResponse* shareMessageToContactResponse = (WBShareMessageToContactResponse*)response;
        NSString* accessToken = [shareMessageToContactResponse.authResponse accessToken];
        if (accessToken)
        {
            self.wbtoken = accessToken;
        }
        NSString* userID = [shareMessageToContactResponse.authResponse userID];
        if (userID) {
            self.wbCurrentUserID = userID;
        }
        [alert show];
    }
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
